//
//  SCBrandBoxVC.m
//  Shuaiche
//
//  Created by zzs on 2017/12/25.
//  Copyright © 2017年 zzs. All rights reserved.
//

#import "SCBrandBoxVC.h"
#import <MagicalRecord/MagicalRecord.h>
#import "SCConstants.h"
#import "Brand+CoreDataProperties.h"
#import "SCBoxCell.h"
#import "SCHttpManager.h"
#import "SCBrandTableHeaderView.h"
#import "BrandUsed+CoreDataClass.h"
#define SCColor(hex) [UIColor colorWithRed:((hex>>16)&0xff)/255. green:((hex>>8)&0xff)/255. blue:(hex&0xff)/255. alpha:1.0]
@interface SCBrandBoxVC ()<NSFetchedResultsControllerDelegate,UIScrollViewDelegate,SCBoxCellDelegate>

@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, strong) NSIndexPath *previousSelectedIndexPath;
@property (nonatomic, weak) SCBrandBoxVC *childBoxVC;
@property (nonatomic, strong) SCBrandTableHeaderView *headerView;
    
@property (nonatomic, assign) BOOL isChild; // 显示

@end

@implementation SCBrandBoxVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.allowsMultipleSelection = NO;
    self.tableView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.tableView.layer.borderWidth = 0.5f;
    self.tableView.estimatedRowHeight = 44.f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.navigationItem.title = @"车型选择";
    if (!_isChild) {
        [self createHeaderView];
    }
}

- (void)setParentId:(int)parentId{
    _parentId = parentId;
    _fetchedResultsController = nil;
    [self.tableView reloadData];
    
    WEAKSELF
    void(^success)(id response) = ^(id response){
        STRONGSELF
        if(!strongSelf){
            Return_From_Block
        }
        if(response){
            
            NSArray *data = response;
            [[NSManagedObjectContext MR_defaultContext] MR_saveWithBlockAndWait:^(NSManagedObjectContext * _Nonnull localContext) {
//                [Brand MR_importFromArray:data inContext:localContext];
                
                [data enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                    if ([obj[kName] length]) {
                        [Brand MR_importFromObject:obj inContext:localContext];
                    } else {
                        NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:obj];
                        data[kName] = @" ";
                        [Brand MR_importFromObject:data inContext:localContext];
                    }
                }];
            }];
            
            NSArray *used = [BrandUsed MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"type==%d",_selectedType]];
            if (used.count != 5) {
                NSArray *titles = @[@"丰田",@"宝马",@"大众",@"奔驰",@"奥迪"];
                for (BrandUsed *us in used) {
                    [us MR_deleteEntity];
                }
                for (int i = 0; i < titles.count; i++) {
                    NSString *title = titles[i];
                    Brand *br = [Brand MR_findFirstByAttribute:@"name" withValue:title];
                    BrandUsed *add = [BrandUsed MR_createEntity];
                    add.id = br.id;
                    add.name = br.name;
                    add.logo = br.logo;
                    add.type = _selectedType;
                    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
                }
            }
            [weakSelf.headerView updateData];
        }
    };
    void(^failure)(NSError *error) = ^(NSError * error){};
  
  NSMutableDictionary *param = [NSMutableDictionary dictionary];
  param[kID] = @(self.parentId);
  [[SCHttpManager shareInstance] httpGet:@"baseprod/cartype/getGroupByParent" param:param completion:^(id response, NSError *error){
    if (!error) {
      success(response);
    }
  }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
    
- (void)createHeaderView {
    SCBrandTableHeaderView *header = [[SCBrandTableHeaderView alloc] init];
    header.delegate = (id<SCBrandTableHeaderViewDelegate>)self;
    header.usedType = _selectedType;
    self.tableView.tableHeaderView = header;
    _headerView = header;
    if (_selectedType == SCCarBrandSelectedTypeSearch) {
        header.title = @"推荐品牌";
    }
}

- (void)brandTableHeaderViewDidSelectedName:(NSString *)brandName brandId:(NSInteger)bid {

    [self pushChildViewControllerWithBrand:(int)bid];
}

#pragma mark -
#pragma mark - UITableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(self.indexTitleType == SCSectionIndexTitleNotLimited){
        return [self.fetchedResultsController.sections count]+1;
    }else if (self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand){
        if(self.casecadeType == SCCasecadeTypeBrand){
            return [self.fetchedResultsController.sections count];
        }else{
            return [self.fetchedResultsController.sections count]+1;
        }
    }
    return [self.fetchedResultsController.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(self.indexTitleType == SCSectionIndexTitleNotLimited){
        if(section==0){
            return 1;
        }else{
            id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section-1];
            return [sectionInfo numberOfObjects];
        }
    }else if (self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand){
        if(self.casecadeType == SCCasecadeTypeBrand){
            id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section];
            return [sectionInfo numberOfObjects];
        }else{
            if(section==0){
                return 1;
            }else{
                id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section-1];
                return [sectionInfo numberOfObjects];
            }
        }
    }
    id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section];
    return [sectionInfo numberOfObjects];
}

- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView{
    if(self.casecadeType!=SCCasecadeTypeBrand){
        return nil;
    }
//    NSMutableArray *indices = [NSMutableArray arrayWithObject:UITableViewIndexSearch];
    NSMutableArray *indices = [NSMutableArray arrayWithCapacity:0];

    if(self.indexTitleType == SCSectionIndexTitleNotLimited){
        [indices addObject:@"*"];
    }
    for (int i=0; i<[self.fetchedResultsController.sections count]; i++) {
        id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][i];
        [indices addObject:sectionInfo.name];
    }
    return indices;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if(self.indexTitleType == SCSectionIndexTitleNotLimited){
        if(section==0){
            return @"*";
        }else{
            id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section-1];
            return sectionInfo.name;
        }
    }else if(self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand){
        if(self.casecadeType == SCCasecadeTypeBrand){
            id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section];
            return sectionInfo.name;
        }else{
            if(section==0){
                return @"*";
            }else{
                id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section-1];
                return sectionInfo.name;
            }
        }
    }
    id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section];
    return sectionInfo.name;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    if([title isEqualToString:@"*"]){
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
//    if (index == 1) {
//        [self.tableView scrollRectToVisible:CGRectMake(0, 0, kSCScreenWidth, 100) animated:YES];
//        return -1;
//    }
    return index-1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *reuseIdentifier = @"boxCellIdentifier";
    SCBoxCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if(!cell){
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([SCBoxCell class]) owner:nil options:nil][0];
    }
    
    if(self.indexTitleType == SCSectionIndexTitleNotLimited || self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand){
        if(self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand &&self.casecadeType == SCCasecadeTypeBrand){
            Brand *brand = [self.fetchedResultsController objectAtIndexPath:indexPath];
            cell.titleLabel.text = brand.name;
            cell.delegate = self;
        }else{
            if(indexPath.section==0){
                if(self.casecadeType == SCCasecadeTypeBrand){
                    cell.titleLabel.text = @"不限品牌";
                }else if (self.casecadeType == SCCasecadeTypeSeries){
                    cell.titleLabel.text = @"不限车系";
                }else if(self.casecadeType == SCCasecadeTypeSpecies){
                    cell.titleLabel.text = @"不限车型";
                }
                
            }else{
                NSIndexPath * newIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section-1];
                Brand *brand = [self.fetchedResultsController objectAtIndexPath:newIndexPath];
                cell.titleLabel.text = brand.name;
                cell.delegate = self;
            }
        }
        if(self.casecadeType == SCCasecadeTypeSeries){
            cell.moreBtn.hidden = NO;
            cell.trailConstraint.constant = 0.25 * kSCScreenWidth;
        }else{
            cell.moreBtn.hidden = YES;
        }
    }else{
        Brand *brand = [self.fetchedResultsController objectAtIndexPath:indexPath];
        cell.titleLabel.text = brand.name;
    }
    cell.titleTrailingConstraint.constant =  0.25 * self.casecadeType * kSCScreenWidth +15;
    if(tableView.indexPathForSelectedRow&&([tableView.indexPathForSelectedRow compare:indexPath]==NSOrderedSame)){
        cell.titleLabel.textColor = SCColor(0xf8603a);
    }else{
        cell.titleLabel.textColor = [UIColor blackColor];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSFetchedResultsController *)fetchedResultsController{
    if(!_fetchedResultsController){
        if(self.casecadeType==SCCasecadeTypeBrand){
            NSPredicate *predict = [NSPredicate predicateWithFormat:@"level == %d AND parentId == %d",(self.casecadeType+1),self.parentId];
            _fetchedResultsController = [Brand MR_fetchAllSortedBy:@"headLetter:1,id:1" ascending:YES withPredicate:predict groupBy:@"headLetter" delegate:self];
        }else{
            NSPredicate *predict = [NSPredicate predicateWithFormat:@"parent.parentId == %d",self.parentId];
            _fetchedResultsController = [Brand MR_fetchAllSortedBy:@"parent.name:0,name:0" ascending:YES withPredicate:predict groupBy:@"parent.name" delegate:self];
        }
    }
    return _fetchedResultsController;
}

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
    if(self.indexTitleType == SCSectionIndexTitleNotLimited){
        indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section+1];
        newIndexPath = [NSIndexPath indexPathForRow:newIndexPath.row inSection:newIndexPath.section+1];
    }else if (self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand){
        if(self.casecadeType != SCCasecadeTypeBrand){
            indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section+1];
            newIndexPath = [NSIndexPath indexPathForRow:newIndexPath.row inSection:newIndexPath.section+1];
        }
    }
    
    switch(type) {
        case NSFetchedResultsChangeInsert:{
            [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
            break;
            
        case NSFetchedResultsChangeDelete:{
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
            break;
            
        case NSFetchedResultsChangeUpdate:{
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
            break;
        case NSFetchedResultsChangeMove:{
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
            break;
    }
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
    if(self.indexTitleType == SCSectionIndexTitleNotLimited){
        sectionIndex = sectionIndex + 1;
    }else if (self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand){
        if(self.casecadeType != SCCasecadeTypeBrand){
            sectionIndex = sectionIndex + 1;
        }
    }
    switch(type) {
        case NSFetchedResultsChangeInsert:{
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationNone];
        }
            break;
            
        case NSFetchedResultsChangeDelete:{
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationNone];
        }
            break;
        case NSFetchedResultsChangeUpdate:{
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationNone];
        }
            break;
        case NSFetchedResultsChangeMove:{//section 没有move
        }
            break;
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
    [self.tableView endUpdates];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.previousSelectedIndexPath){
        SCBoxCell *previousCell = [tableView cellForRowAtIndexPath:self.previousSelectedIndexPath];
        previousCell.titleLabel.textColor = [UIColor blackColor];
    }
    SCBoxCell *cell = [tableView cellForRowAtIndexPath:[tableView indexPathForSelectedRow]];
    cell.titleLabel.textColor = SCColor(0xf8603a);
    self.previousSelectedIndexPath = indexPath;
    if(self.indexTitleType == SCSectionIndexTitleNotLimited || self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand){
        if(indexPath.section == 0 && !(self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand &&self.casecadeType == SCCasecadeTypeBrand)){
            if(self.casecadeType == SCCasecadeTypeBrand){
                if(self.indexTitleType == SCSectionIndexTitleNotLimited){
                    if(self.completion){//这里的self.parentId为0
                        self.completion(self.parentId, 0,0,nil,nil,nil);
                    }
                }
            }else if (self.casecadeType == SCCasecadeTypeSeries){
                if(self.completion){
                    Brand *brand = [Brand MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"id == %d",self.parentId]];
                    self.completion(self.parentId, 0,0,brand.name,nil,nil);
                    [self saveBrandUsed:brand];
                }
            }else{
                if(self.completion){
                    Brand *series = [Brand MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"id == %d",self.parentId]];
                    Brand *brand = [Brand MR_findFirstWithPredicate: [NSPredicate predicateWithFormat:@"id == %d",series.parent.parentId]];
                    self.completion(series.parent.parentId, self.parentId,0,brand.name,series.name,nil);
//                    [_headerView saveUsedBrand:brand];
                    [self saveBrandUsed:brand];
                }
            }
            if (!_stayHere) {
                [self.navigationController popViewControllerAnimated:YES];
            }
            return;
        }
        if(self.casecadeType == SCCasecadeTypeBrand){
            
        } else if(self.casecadeType == SCCasecadeTypeSeries){
            if(!self.childViewControllers.count){
                if(self.completion){
                    NSIndexPath *seriesIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section-1];
                    Brand *series = [self.fetchedResultsController objectAtIndexPath:seriesIndexPath];
                    Brand *brand = [Brand MR_findFirstWithPredicate: [NSPredicate predicateWithFormat:@"id == %d",self.parentId]];
                    self.completion(self.parentId, series.id,0,brand.name,series.name,nil);
//                    [_headerView saveUsedBrand:brand];
                    [self saveBrandUsed:brand];
                }
                if (!_stayHere) {
                    [self.navigationController popViewControllerAnimated:YES];
                }
                return;
            }
        }else{
            if(self.completion){
                Brand *series = [Brand MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"id == %d",self.parentId]];
                Brand *brand = [Brand MR_findFirstWithPredicate: [NSPredicate predicateWithFormat:@"id == %d",series.parent.parentId]];
                NSIndexPath *seriesIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section-1];
                Brand *species = [self.fetchedResultsController objectAtIndexPath:seriesIndexPath];
                self.completion(series.parent.parentId, self.parentId,species.id,brand.name,series.name,species.name);
//                [_headerView saveUsedBrand:brand];
                [self saveBrandUsed:brand];
            }
            if (!_stayHere) {
                [self.navigationController popViewControllerAnimated:YES];
            }
            
            return;
        }
        
        if(self.childViewControllers.count){
            [self reloadCellAtIndexPath:indexPath];
        }else{
            [self pushChildVCAtIndexPath:indexPath];
        }
    }else{
        if(self.casecadeType == SCCasecadeTypeSpecies){
            if(self.success){
                NSPredicate *predict = [NSPredicate predicateWithFormat:@"id == %d",self.parentId];
                Brand *series = [Brand MR_findFirstWithPredicate:predict];
                Brand *species = [self.fetchedResultsController objectAtIndexPath:indexPath];
                Brand *brand = [Brand MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"id == %d",series.parent.parentId]];
                self.success(series.parent.parentId, self.parentId, species.id, brand.name, series.name, species.name);
                [self saveBrandUsed:brand];
            }
            if(self.completion){
                NSPredicate *predict = [NSPredicate predicateWithFormat:@"id == %d",self.parentId];
                Brand *series = [Brand MR_findFirstWithPredicate:predict];
                Brand *species = [self.fetchedResultsController objectAtIndexPath:indexPath];
                Brand *brand = [Brand MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"id == %d",series.parent.parentId]];
                self.completion(series.parent.parentId, self.parentId, species.id, brand.name, series.name, species.name);
//                [_headerView saveUsedBrand:brand];
                [self saveBrandUsed:brand];
            }
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }else{
            if(!self.childViewControllers.count){
                [self pushChildVCAtIndexPath:indexPath];
            }else{
                [self reloadCellAtIndexPath:indexPath];
            }
        }
    }
}

- (void)reloadCellAtIndexPath:(NSIndexPath *)indexPath{
    if(self.indexTitleType == SCSectionIndexTitleNotLimited){
        indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section-1];
    }else if(self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand){
        if(self.casecadeType != SCCasecadeTypeBrand){
            indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section-1];
        }
    }
    Brand *brand = [self.fetchedResultsController objectAtIndexPath:indexPath];
    [self.childBoxVC setParentId:brand.id];
    if(self.childBoxVC.childViewControllers.count){
        UIViewController *childVC =self.childBoxVC.childViewControllers[0];
        [self dismissViewController:childVC animation:NO completion:nil];
    }
}

- (void)dismissViewController:(UIViewController *)vc animation:(BOOL)animation completion:(void (^)(void))completion{
    if(!animation){
        [vc willMoveToParentViewController:nil];
        [vc.view removeFromSuperview];
        [vc didMoveToParentViewController:nil];
        [vc removeFromParentViewController];
    }
}

- (void)pushChildVCAtIndexPath:(NSIndexPath *)indexPath{
    if(self.indexTitleType == SCSectionIndexTitleNotLimited){
        indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section-1];
    }else if(self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand){
        if(self.casecadeType != SCCasecadeTypeBrand){
            indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section-1];
        }
    }
    Brand *brand = [self.fetchedResultsController objectAtIndexPath:indexPath];
    [self pushChildViewControllerWithBrand:brand.id];
}

- (void)pushChildViewControllerWithBrand:(int)bid {
    SCBrandBoxVC *childBoxVC = [[SCBrandBoxVC alloc] init];
    childBoxVC.stayHere = _stayHere;
    childBoxVC.isChild = YES;
    childBoxVC.completion = self.completion;
    childBoxVC.success = self.success;
    childBoxVC.casecadeType = self.casecadeType+1;
    childBoxVC.selectedType = _selectedType;
    if(self.indexTitleType == SCSectionIndexTitleNotLimited||self.indexTitleType == SCSectionIndexTitleNotLimitedExceptBrand){
        childBoxVC.indexTitleType = SCSectionIndexTitleNotLimited;
    }
    childBoxVC.parentId = bid;
    //childBoxVC.parentName = brand.name;
    [self addChildViewController:childBoxVC];
    self.childBoxVC = childBoxVC;
    [self.view addSubview:childBoxVC.view];
    CGRect frame = CGRectMake(kSCScreenWidth, 0, kSCScreenWidth, kSCScreenHeight);
    [childBoxVC.view setFrame:frame];
    frame.origin.x = 0.25 * kSCScreenWidth;
    [UIView animateWithDuration:0.15 animations:^{
        [childBoxVC.view setFrame:frame];
    } completion:^(BOOL finished) {
        [childBoxVC didMoveToParentViewController:self];
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    static BOOL isAnimated = NO;
    if(self.childViewControllers.count){
        if(isAnimated){
            return;
        }
        UIViewController *childVC =self.childViewControllers[0];
        [childVC willMoveToParentViewController:nil];
        [UIView animateWithDuration:0.3 animations:^{
            isAnimated = YES;
            [childVC.view setFrame:CGRectMake(CGRectGetWidth([UIScreen mainScreen].bounds), 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds))];
        } completion:^(BOOL finished) {
            [childVC.view removeFromSuperview];
            [childVC didMoveToParentViewController:nil];
            [childVC removeFromParentViewController];
            if(self.tableView.indexPathForSelectedRow){
                SCBoxCell *cell = [self.tableView cellForRowAtIndexPath:self.tableView.indexPathForSelectedRow];
                cell.titleLabel.textColor = [UIColor blackColor];
                [self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:NO];
            }
            _headerView.hasSelected = NO;
            isAnimated = NO;
        }];
    }
}

- (void)showSpeciesWithCell:(SCBoxCell *)cell{
    if(self.previousSelectedIndexPath){
        SCBoxCell *previousCell = [self.tableView cellForRowAtIndexPath:self.previousSelectedIndexPath];
        previousCell.textLabel.textColor = [UIColor blackColor];
    }
    cell.titleLabel.textColor = SCColor(0xf8603a);
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    self.previousSelectedIndexPath = indexPath;
    if(!indexPath){
        return;
    }
    [self pushChildVCAtIndexPath:indexPath];
}

- (void)saveBrandUsed:(Brand *)br {
    
    if (br.id == 0) {
        return;
    }
    
    BrandUsed *first = [BrandUsed MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"type==%d&&id==%d",_selectedType,br.id]];
    if (first) {
        [first MR_deleteEntity];
    } else {
        first = [BrandUsed MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"type==%d",_selectedType]];
        [first MR_deleteEntity];
    }
    BrandUsed *last = [BrandUsed MR_createEntity];
    last.id = br.id;
    last.name = br.name;
    last.logo = br.logo;
    last.type = _selectedType;
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
}

@end
